package com.hmall.item.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.time.LocalDateTime;
import java.util.List;


@Service
public class ItemService extends ServiceImpl<ItemMapper, Item> implements IItemService {
    @Autowired
    private ItemMapper itemMapper;

    public PageDTO<Item> pageList(Long page, Long size) {
        //构建分页查询
        Page pages =new Page(page,size);
        //条件构造器
        LambdaQueryWrapper<Item> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Item::getId);
        //查询
        Page selectPage = itemMapper.selectPage(pages, queryWrapper);

        //获取及记录数
        long total = selectPage.getTotal();
        //获取当前页数据
        List records = selectPage.getRecords();
        //封装返回
        return new PageDTO<Item>(total,records);
    }

    /**
     * 处理超时订单回复库存
     *
     * @param itemId
     * @param num
     */
    @Override
    public void refundItemStock(Long itemId, Integer num) {
        itemMapper.refund(itemId,num);
    }


    //修改商品
    @Override
    public void updateItem(Item item){
        itemMapper.updateById(item);
    }

    //根据ID删除商品
    @Override
    public void deleteItem(Integer itemId){
        itemMapper.deleteById(itemId);
    }


    //注入rabbittemplate-消息对象
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 基本消息队列
     */

    public void testSimpleQueue(Item item){
        String queueName = "item.queue";
        String msg = JSON.toJSONString(item);
        //参数一：消息队列名  参数二：消息内容
        rabbitTemplate.convertAndSend(queueName,msg);
    }
    /**
     * 上架下架商品
     * @param itemId
     * @param status
     */
    @Override
    public void enableAndDisableItem(Long itemId, Integer status) {
        Item item = itemMapper.selectById(itemId);
        if (item != null) {
            item.setStatus(status);
            itemMapper.updateById(item);
        }
        testSimpleQueue(item);
    }

    /**
     * 根据id查询商品
     * @param id
     * @return
     */
    @Override
    public Item getByItemId(Long id) {
        return itemMapper.selectItemById(id);
    }

    @Override
    public int addItem(Item item) {
        item.setCreateTime(LocalDateTime.now());
        item.setUpdateTime(LocalDateTime.now());
        return itemMapper.insertProduct(item);
    }

}
